<template>
  <van-button
    :icon="value ? 'star' : 'star-o'"
    :class="{
      collected: value
      }"
    @click="onCollect"
    :loading="loading"
  />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'
export default {
  name: 'CollectArticle',
  props: {
    value: {
      type: Boolean,
      require: true
    },
    articleId: {
      type: [String, Number, Object],
      require: true
    }
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    async onCollect () {
      this.loading = true
      try {
        // 如果已收藏，则取消收藏
        if (this.value) {
          await deleteCollect(this.articleId)
        } else {
          // 添加收藏
          await addCollect(this.articleId)
        }
        this.$emit('input', !this.value)

        // 提示这里用!this.value，是因为上面传递给父组件的执行代码，还没执行完，当前页面数据还没有刷新。拿到的this.value是没有更新后的数据
        this.$toast.success(!this.value ? '收藏成功' : '取消收藏')
      } catch (err) {
        this.$toast.fail('收藏操作失败')
      }
      this.loading = false
    }
  }
}
</script>

<style scoped lang="less">
.collected {
  .van-icon {
    color: #ffa500;
  }
}

</style>
